import 'package:flutter/material.dart';
import 'package:flutter_base/base/controller/base_controller.dart';
import 'package:flutter_base/http/http_export.dart';
import 'package:flutter_base/pages/chat/model/model_chat_base.dart';
import 'package:flutter_base/pages/chat/model/model_chat_clarification.dart';
import 'package:flutter_base/pages/chat/model/model_chat_confirmation.dart';
import 'package:flutter_base/pages/chat/model/model_chat_test_created.dart';
import 'package:flutter_base/pages/chat/model/model_chat_too_short.dart';
import 'package:get/get.dart';
import 'dart:async';

class DigitalHumanChatLogic extends BaseController {
  // 消息列表
  List<ModelChatBase> messages = [];

  // 输入控制器
  final TextEditingController inputController = TextEditingController();

  // 滚动控制器，用于滚动到底部
  final ScrollController scrollController = ScrollController();

  // 是否显示发送按钮
  RxBool showSendButton = false.obs;

  // 是否正在加载历史消息
  bool isLoadingHistory = false;
  
  // 存储问题回答情况的Map
  // key: sessionId, value: Map<问题ID, 回答>
  final Map<String, Map<String, String>> _answeredQuestions = {};
  
  // 存储每个会话当前显示的问题索引
  // key: sessionId, value: 当前问题索引
  final Map<String, int> _currentQuestionIndices = {};
  
  // 当前活动问题信息
  String? _activeSessionId;
  String? _activeQuestionId;
  int? _activeDetectedTypeId;
  
  // 是否有活动问题等待回答
  bool get hasActiveQuestion => _activeSessionId != null && _activeQuestionId != null;

  @override
  void onInit() {
    super.onInit();
    inputController.addListener(_onInputChanged);

    // 初始化模拟消息
    _initMockMessages();
    // executeInitMethod(psychologyCreate);，；
    // psychologyCreate();
  }

  @override
  void onReady() {
    super.onReady();
    // 加载历史消息
    // loadHistoryMessages();
  }

  @override
  void onClose() {
    inputController.removeListener(_onInputChanged);
    inputController.dispose();
    scrollController.dispose();
    super.onClose();
  }

  Future psychologyCreate(dynamic params) async {
    HttpResponse response = await HttpManager().post(
      API.psychologyCreate,
      params: params,
    );
    if (response.isSuccess) {
      ModelChatBase modelChatBase = ModelChatBase.fromJson(response.data);
      if (modelChatBase.stage == 'need_confirmation') {
        // ;
        messages.add(ModelChatConfirmation.fromJson(response.data));
      } else if (modelChatBase.stage == 'need_clarification') {
        // ;
        messages.add(ModelChatClarification.fromJson(response.data));
      } else if (modelChatBase.stage == 'inappropriate_content' ||
          modelChatBase.stage == 'invalid_input' ||
          modelChatBase.stage == 'vague_input' ||
          modelChatBase.stage == 'input_too_short') {
        messages.add(ModelChatTooShort.fromJson(response.data));
      } else if (modelChatBase.stage == 'test_created') {
        // ;
        messages.add(ModelChatTestCreated.fromJson(response.data));
      }

      update();

      ///stage  : inappropriate_content invalid_input vague_input input_too_short  为 ModelChatTooShort
      /// stage : need_confirmation  为 ModelChatConfirmation
      /// stage : need_clarification  为 ModelChatClarification
      ///自定义类型  stage ： user 为用户发送
      ///stage:  hello  为欢迎语

      _scrollToBottom();
    }
  }

  // 监听输入变化
  void _onInputChanged() {
    showSendButton.value = inputController.text.trim().isNotEmpty;
  }

  // 发送消息
  void sendMessage({String? message}) async {
    final text = message ?? inputController.text.trim();
    if (text.isEmpty) return;

    if (message == null) {
      // 清空输入
      inputController.clear();
    }


    // 创建用户消息
    final userMessage = ModelChatBase(
      message: text,
      stage: 'user',
    );

    // 添加到消息列表
    messages.add(userMessage);
    update();

    // 滚动到底部
    _scrollToBottom();
    psychologyCreate({'description': text}).then((value) {
      // inputController.text = '';
    });
  }

  // 设置当前活动问题
  void setActiveQuestion({
    required String sessionId,
    required String questionId,
    int? detectedTypeId,
  }) {
    _activeSessionId = sessionId;
    _activeQuestionId = questionId;
    _activeDetectedTypeId = detectedTypeId;
    update();

  }
  
  // 提交文本答案
  void submitTextAnswer(String answer) {
    if (answer.isEmpty || !hasActiveQuestion) return;
    
    // 清空输入框
    inputController.clear();
    
    // 提交答案
    submitAnswer(
      sessionId: _activeSessionId!,
      questionId: _activeQuestionId!,
      answer: answer,
      detectedTypeId: _activeDetectedTypeId,
    );
  }
  
  // 获取当前需要回答的问题索引
  int getCurrentQuestionIndex(String sessionId) {
    // 如果没有记录当前会话的问题索引，则默认返回0（第一个问题）
    return _currentQuestionIndices[sessionId] ?? 0;
  }
  
  // 获取指定会话的答案
  Map<String, String> getAnswers(String sessionId) {
    return _answeredQuestions[sessionId] ?? {};
  }
  
  // 提交问题答案
  void submitAnswer({
    required String sessionId,
    required String questionId,
    required String answer,
    int? detectedTypeId,
  }) {
    // 初始化会话的回答Map（如果不存在）
    _answeredQuestions[sessionId] ??= {};
    
    // 存储回答
    _answeredQuestions[sessionId]![questionId] = answer;
    
    // 初始化当前问题索引（如果不存在）
    _currentQuestionIndices[sessionId] ??= 0;
    
    // 查找当前会话的所有问题
    ModelChatClarification? clarificationMessage;
    for (var message in messages) {
      if (message is ModelChatClarification && message.sessionId == sessionId) {
        clarificationMessage = message;
        break;
      }
    }
    
    if (clarificationMessage != null) {
      // 增加当前问题索引
      _currentQuestionIndices[sessionId] = (_currentQuestionIndices[sessionId] ?? 0) + 1;
      
      // 如果已回答所有问题，则发送整个回答集给服务器
      if (_currentQuestionIndices[sessionId]! >= (clarificationMessage.clarifyQuestions?.length ?? 0)) {
        // 创建用户回答消息
        final userMessage = ModelChatBase(
          message: "已回答全部问题",
          stage: 'user',
        );
        
        // 添加到消息列表
        messages.add(userMessage);
        
        // 准备发送给服务器的数据
        final params = {
          'description': clarificationMessage.originalQuestion,
          'session_id': sessionId,
          'confirmed_type_id': detectedTypeId,
          'clarify_responses': _answeredQuestions[sessionId],
        };
        
        // 清除活动问题信息
        _activeSessionId = null;
        _activeQuestionId = null;
        _activeDetectedTypeId = null;
        
        // 发送请求
        psychologyCreate(params);
      } else {
        // 如果还有更多问题，则更新UI以显示下一个问题
        // 获取下一个问题
        final nextQuestionIndex = _currentQuestionIndices[sessionId]!;
        if (nextQuestionIndex < (clarificationMessage.clarifyQuestions?.length ?? 0)) {
          final nextQuestion = clarificationMessage.clarifyQuestions![nextQuestionIndex];
          
          // 更新活动问题
          setActiveQuestion(
            sessionId: sessionId,
            questionId: nextQuestion?.id ?? '',
            detectedTypeId: detectedTypeId,
          );
        }
        
        update();
      }
      
      // 滚动到底部
      _scrollToBottom();
    }
  }

  // 滚动到底部
  void _scrollToBottom() {
    // 使用Future.delayed确保在更新UI后滚动
    Future.delayed(const Duration(milliseconds: 100), () {
      if (scrollController.hasClients) {
        scrollController.animateTo(
          scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  // 初始化模拟消息
  void _initMockMessages() {
    messages = [
      ModelChatBase(
        stage: 'hello',
        message:
            'Hello, I am your mental AI assistant. What would you like to explore? Feel free to ask me any questions!',
      ),
    ];
  }
  // [log] uri: http://192.168.5.180:9999/api/psychology/ai/create
  // [log] Response Text:
  // [log] {"code":200,"message":"ok","data":{"detected_type_id":3,"stage":"test_created","test_id":16}}
}
